<?php
/**
 * Created by PhpStorm.
 * User: 沁塵
 * Date: 2019/4/20
 * Time: 19:57
 */

namespace app\api\controller\v1;

use app\api\model\Account;
use app\api\model\AccountArticle;
use app\api\model\AccountProfit;
use app\api\model\Config;
use app\api\model\SnycDistribute;
use app\lib\exception\sync\syncException;
use think\Request;

class Accounts
{
    public function getAccountList()
    {
        $pageSize = $params['pageSize'] ?? 50;
        $list = Account::where('platform','京东')->order("id")
            ->paginate($pageSize);

        if (!empty($list)) {
            foreach ( $list as &$li) {
                $count = SnycDistribute::where("account_id", $li["id"])->where("status", 3)->count();
                $li["count"] = $count;
            }
        }

        return writeJson(200,$list,'用户列表！');
    }

    public function updateCookie(Request $request)
    {
        $params = $request->post();
        $account = new Account();
        $account->save($params, ['id' => $params['id'], 'platform' => '京东']);
        return writeJson(200, '', '更新账户成功');
    }

    public function getAccount(Request $request)
    {
        $params = $request->get();
        $account = Account::where('app_id',$params['app_id'])->where('platform','京东')->find();
        if(empty($account)){
            return writeJson(400, [], '账户不存在');
        }
        return writeJson(200, $account, '获取成功');
    }


    public function addAccount(Request $request)
    {
        $params = $request->post();
        if (empty($params['account'])) {
            return writeJson(400, [], '账户不能为空');
        }
        if (empty($params['password'])) {
            return writeJson(400, [], '账户密码不能为空');
        }
        if (empty($params['name'])) {
            return writeJson(400, [], '名字不能为空');
        }
        if (empty($params['cookie'])) {
            return writeJson(400, [], 'cookie不能为空');
        }
        if (empty($params['app_id'])) {
            return writeJson(400, [], 'app_id不能为空');
        }
        if (empty($params['platform'])) {
            return writeJson(400, [], 'platform不能为空');
        }
        if (empty($params['uid'])) {
            return writeJson(400, [], 'uid不能为空');
        }
        if (empty($params['category'])) {
            return writeJson(400, [], '类目不能为空');
        }
        $data = [
            'account' => $params['account'],
            'password' => $params['password'],
            'name' => $params['name'],
            'cookie' => $params['cookie'],
            'app_id' => $params['app_id'],
            'platform' => $params['platform'],
            'uid' => $params['uid'],
            'category' => $params['category'],
            'mobile' => empty($params['mobile']) ? null : $params['mobile'],
            'real_name' => empty($params['real_name']) ? null : $params['real_name'],
            'sound_model' => empty($params['sound_model']) ? null : $params['sound_model'],
            'model_name' => empty($params['model_name']) ? null : $params['model_name'],
            'picture' => empty($params['picture']) ? null : $params['picture'],
            'ali_authorize' => empty($params['ali_authorize']) ? null : $params['ali_authorize'],
            'ascription' => empty($params['ascription']) ? null : $params['ascription'],
            'team' => empty($params['team']) ? null : $params['team'],
            'create_time' => date("Y-m-d H:i:s")
        ];
        $res = Account::create($data);
        return writeJson(200, $res, '添加成功');
    }

    // 通过插件更新逛逛账号基础信息
    public function updateAccountByUnit(Request $request){
        $params = $request->post();

        $account = Account::where('app_id',$params['app_id'])->where('platform','逛逛')->findOrEmpty();
        if($account->isEmpty()){
            return writeJson(200, null, '暂未找到对应账号');
        }

        $account->name = $params['nickname'];
        if(!empty($params['level'])){
            $account->level =  $params['level'];
        }

        $account->save();

        // 增加收益记录

        if(!empty($params['profits'])) {
            $profits = $params['profits'];
            foreach ($profits as $profit){
                $profit_exists = AccountProfit::where('app_id',$profit['app_id'])
                    ->where('type',$profit['type'])
                    ->where('day',$profit['day'])
                    ->findOrEmpty();

                if($profit_exists->isEmpty()){
                    AccountProfit::create($profit);
                }
            }
        }



        if(!empty($params['articles'])) {
            $articles = $params['articles'];
            foreach ($articles as $article){
                $article_exists = AccountArticle::where('app_id',$article['app_id'])
                    ->where('article_id',$article['article_id'])
                    ->findOrEmpty();

                if($article_exists->isEmpty()){
                    AccountArticle::create($article);
                }else{
                    $article_exists->view = $article['view'];
                    $article_exists->status = $article['status'];

                    $article_exists->save();
                }
            }
        }


        return writeJson(200, null, '更新成功');



    }

    public function updateAccount(Request $request)
    {
        $params = $request->post();
        if (empty($params['id'])) {
            return writeJson(400, [], '缺少参数id');
        }
        if (empty($params['account'])) {
            return writeJson(400, [], '账户不能为空');
        }
        if (empty($params['password'])) {
            return writeJson(400, [], '账户密码不能为空');
        }
        if (empty($params['name'])) {
            return writeJson(400, [], '名字不能为空');
        }
        if (empty($params['cookie'])) {
            return writeJson(400, [], 'cookie不能为空');
        }
        if (empty($params['app_id'])) {
            return writeJson(400, [], 'app_id不能为空');
        }
        if (empty($params['platform'])) {
            return writeJson(400, [], 'platform不能为空');
        }
        if (empty($params['uid'])) {
            return writeJson(400, [], 'uid不能为空');
        }
        if (empty($params['category'])) {
            return writeJson(400, [], '类目不能为空');
        }
        $data = [
            'account' => $params['account'],
            'password' => $params['password'],
            'name' => $params['name'],
            'cookie' => $params['cookie'],
            'app_id' => $params['app_id'],
            'platform' => $params['platform'],
            'uid' => $params['uid'],
            'category' => $params['category'],
            'mobile' => empty($params['mobile']) ? null : $params['mobile'],
            'real_name' => empty($params['real_name']) ? null : $params['real_name'],
            'sound_model' => empty($params['sound_model']) ? null : $params['sound_model'],
            'model_name' => empty($params['model_name']) ? null : $params['model_name'],
            'picture' => empty($params['picture']) ? null : $params['picture'],
            'ali_authorize' => empty($params['ali_authorize']) ? null : $params['ali_authorize'],
            'team' => empty($params['team']) ? null : $params['team'],
            'update_time' => date("Y-m-d H:i:s")
        ];
        $account = new Account();
        $res = $account->save($data,['id' => $params['id']]);
        return writeJson(200, $res, '修改成功');
    }


    public function getCategory()
    {
        $category = Config::where('name','category')->column('value');
        return writeJson(200, $category, '获取成功');
    }


    public function getTopic()
    {
        $topic = Config::where('name','jd_topic')->column('value');
        return writeJson(200, $topic, '获取成功');
    }

    public function getPlatform()
    {
        $platform = Config::where('name','platform')->column('value');
        return writeJson(200, $platform, '获取成功');
    }

    public function getTag()
    {
        $tagArr = Config::where('name','jd_tag')->select();
        $tag = [];
        foreach ($tagArr as $v) {
            $tag[$v['key']][] = $v['value'];
        }

        return writeJson(200, $tag, '获取成功');
    }


    public function getModel()
    {
        $model = Config::field('key,value')->where('name','model')->select();
        return writeJson(200, $model, '获取成功');
    }

    // 写入数组到文件
    function writeArrayToFile($filePath, array $array) {
        $content = json_encode($array);
        file_put_contents($filePath, $content);
    }

    // 从文件读取数组
    function readArrayFromFile($filePath) {
        if (file_exists($filePath)) {
            $content = file_get_contents($filePath);
            $array = json_decode($content, true);
            return $array;
        } else {
            return [];
        }
    }

    public function plugAdd(Request $request)
    {

        $params = $request->post();
        $info = Account::where("app_id", $params["app_id"])->findOrEmpty();
        if ($info->isEmpty()) {
            $add = [];
            $add["account"] = $params["account"];
            $add["password"] = $params["password"];
            $add["name"] = $params["name"];
            $add["app_id"] = $params["app_id"];
            $add["mobile"] = $params["mobile"];
            $add["platform"] = "京东";
            $add["remark"] = 1;
            $add["category"] = "母婴,美妆,潮女,家居,美食";
            $res = Account::create($add);
            return writeJson(200, $res, '添加成功');
        } else {
            return writeJson(200, "", '该号已存在');
        }
    }

    public function plugEnable(Request $request)
    {
        $params = $request->get();
        $account = new Account();
        $account->where("id", $params["id"])->update(['remark' => NULL]);
        return writeJson(200, '', '启用成功');
    }

    public function plugUnenable(Request $request)
    {
        $params = $request->get();
        $account = new Account();
        $remark = "1";
        if (isset($params['remark']) && $params['remark'] != "") {
            $remark = $params['remark'];
        }
        $account->save($params, ['id' => $params['id'], 'remark' => $remark]);
        return writeJson(200, '', '停用成功');
    }
}